//
//  WKSearchViewController.m
//  WeKeTang
//
//  Created by ichina on 2017/8/23.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKSearchViewController.h"
#import "WKTableView.h"
#import "WKTableViewCell.h"
#import "WKNetworkTools.h"
#import "WKLoginHandel.h"
#import "WKUniversal.h"
#import "WKSearchResultCell.h"
#import "WKSearchResultModel.h"
#import "WKHomeViewController.h"
#import "WKPlayerViewController.h"

static  NSString *const cellID = @"search";

@interface WKSearchViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet WKTableView *mainTableView;
@property (nonatomic, strong) UITextField *TFsearch;
@property (weak, nonatomic) IBOutlet UIButton *searchHistor;
@property (weak, nonatomic) IBOutlet UIButton *deleteHistorBtn;
@property (nonatomic, strong) UIButton *btnBack;
@property (nonatomic, strong) UITableView *TBSearch;
@property (nonatomic, strong) YYLabel *tipLabel;
@property (nonatomic, strong) NSMutableArray *historyList;
@property (nonatomic, strong) NSArray *searchResultList;
@property (nonatomic, strong) YYLabel *footerLabel;
@property (nonatomic, strong) UIImageView *maskImgView;
@property (nonatomic, strong) UIView *titleView;
@property (nonatomic, strong) UIView *lineView;

@end

@implementation WKSearchViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.TFsearch becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.TFsearch endEditing:YES];
    [self.TFsearch resignFirstResponder];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.navgationBar.barTintColor=[UIColor whiteColor];
    [self setRightButtonWithTittle:@"搜索"
                             color:RGBColor(75, 167, 184)
                            target:self
                            action:@selector(searchAction:)];
    [self.navgationBar addSubview:self.TFsearch];
    [self.navgationBar addSubview:self.btnBack];
    [self setupUI];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textfiledChangeAction:) name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)setupUI{
    
    [self.mainTableView registerClass:[WKTableViewCell class] forCellReuseIdentifier:cellID];
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kDeviceScreenWidth, 0)];
    footerView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideenKeyboard:)];
    self.mainTableView.tableFooterView = footerView;
    self.mainTableView.tableFooterView.userInteractionEnabled = YES;
    [ self.mainTableView.tableFooterView addGestureRecognizer:tapGestureRecognizer];
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"history"]) {
        
        NSArray *list = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:@"history"];
        
        self.historyList = [[NSMutableArray alloc]initWithArray:list];
        NSLog(@"记录:-----------%@",self.historyList);
        
    }else{
        self.historyList = [[NSMutableArray alloc]init];
    }
}
#pragma mark - 搜索
- (void)searchAction:(UIButton*)sender{
    if (self.TFsearch.text.length == 0) {
        [self showCustomAlertMessage:@"搜索内容不能为空"];
        return;
    }
     NSLog(@"搜索历史1:%@",self.historyList);
        //开始搜索
    [self loadSearchData];
    [self searchAction];
    [self.TFsearch resignFirstResponder];
    [self.TFsearch endEditing:YES];
    for (NSString *historyStr in self.historyList) {
        if ([historyStr isEqualToString:self.TFsearch.text]) {
            return;
        }
    }
    [self.historyList addObject:self.TFsearch.text];
    [[NSUserDefaults standardUserDefaults] setObject:self.historyList forKey:@"history"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.mainTableView reloadData];
    NSLog(@"搜索历史2： %@",self.historyList);
    
}
#pragma mark - UITextFieldDelegate点击键盘搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (self.TFsearch.text.length == 0) {
        [self showCustomAlertMessage:@"搜索内容不能为空"];
        return NO;
    }
    NSLog(@"搜索历史1:%@",self.historyList);
    //开始搜索
    [self loadSearchData];
    [self searchAction];
    [self.TFsearch resignFirstResponder];
    [self.TFsearch endEditing:YES];
    for (NSString *historyStr in self.historyList) {
        if ([historyStr isEqualToString:self.TFsearch.text]) {
            
            return NO;
        }
    }
    [self.historyList addObject:self.TFsearch.text];
    [[NSUserDefaults standardUserDefaults] setObject:self.historyList forKey:@"history"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.mainTableView reloadData];
    NSLog(@"搜索历史2：%@",self.historyList);
    [self.TFsearch resignFirstResponder];
    [self.TFsearch endEditing:YES];
    return YES;
}

#pragma mark - 请求搜索结果
- (void)loadSearchData{
    __weak typeof(self) weakSelf = self;
    NSString *phpsessid = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"search" forKey:@"commandid"];
    [para setObject:phpsessid forKey:@"phpsessid"];
    [para setObject:self.TFsearch.text forKey:@"searchContent"];
    [[WKNetworkTools shareManger]setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain completionHandler:^(id responseObject) {
    } errorHandler:^(NSError *error) {
        //[weakSelf showCustomAlertMessage:@"网络错误"];
    } finishHandler:^(id responseObject) {
        NSLog(@"搜索:%@",responseObject);
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *head = dict[@"head"];
        NSArray *bodyList = dict[@"body"];
        NSString *statuscode = head[@"statuscode"];
        NSMutableArray *mArray = [NSMutableArray array];
        if ([statuscode intValue] == 100) {
            for (NSInteger i = 0; i< bodyList.count; i++) {
                WKSearchResultModel *model = [WKSearchResultModel mj_objectWithKeyValues:bodyList[i]];
                [mArray addObject:model];
            }
            weakSelf.searchResultList = mArray;
            
            [weakSelf.TBSearch reloadData];
        }else{
//            [weakSelf showCustomAlertMessage:@"搜索失败"];
            self.TBSearch.hidden = YES;
            self.titleView.hidden = YES;
            self.lineView.hidden = YES;
            self.maskImgView.hidden = NO;
            self.headerView.hidden = YES;
        }
    }];
}
- (void)setSearchResultList:(NSArray *)searchResultList{
    
    _searchResultList = searchResultList;

    self.tipLabel.text = [NSString stringWithFormat:@"共找到%ld个相关课程",self.searchResultList.count];
    NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:self.tipLabel.text];
    [hintString addAttribute:NSForegroundColorAttributeName value:RGBColor(0, 164, 184) range:NSMakeRange(3,self.tipLabel.text.length-8)];
    [hintString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, self.tipLabel.text.length)];
    
    self.tipLabel.attributedText = hintString;

    if (self.searchResultList.count == 0) {
        self.maskImgView.hidden = NO;
        self.headerView.hidden = YES;
        self.lineView.hidden = YES;
        
    }
}
- (void)searchAction{
    
    self.searchHistor.hidden = YES;
    self.deleteHistorBtn.hidden = YES;
    self.mainTableView.hidden = YES;
    self.headerView.hidden = YES;
    
    [self.titleView removeFromSuperview];
    self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 65, kDeviceScreenWidth, 31)];
    self.titleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.titleView];
    
    [self.tipLabel removeFromSuperview];
    self.tipLabel = [[YYLabel alloc]initWithFrame:CGRectMake(10, 5, 150, 31-10)];
    self.tipLabel.font = [UIFont systemFontOfSize:14];
    self.tipLabel.textColor = [UIColor colorWithHexString:@"#666666"];
    [self.titleView addSubview:self.tipLabel];
    
    [self.lineView removeFromSuperview];
    self.lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 96, kDeviceScreenWidth, 0.5)];
    self.lineView.backgroundColor = [UIColor colorWithHexString:@"#999999"];
    [self.view addSubview:self.lineView];
    
    [self.TBSearch removeFromSuperview];
    self.TBSearch = [[UITableView alloc]initWithFrame:CGRectMake(0, 96.5, kDeviceScreenWidth, kDeviceScreenHeight - 65) style:UITableViewStylePlain];
    self.TBSearch.delegate = self;
    self.TBSearch.dataSource = self;
    [self.view addSubview:self.TBSearch];
    [self.TBSearch registerNib:[UINib nibWithNibName:@"WKSearchResultCell" bundle:nil] forCellReuseIdentifier:@"searchCell"];
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kDeviceScreenWidth, 30)];
    self.footerLabel = [[YYLabel alloc]initWithFrame:CGRectMake(0, 0, kDeviceScreenWidth, 21)];
    self.footerLabel.center = footView.center;
    self.footerLabel.text = @"已加载全部内容";
    self.footerLabel.textColor = [UIColor colorWithHexString:@"#666666"];
    self.footerLabel.textAlignment = NSTextAlignmentCenter;
    self.footerLabel.font = [UIFont systemFontOfSize:13];
    [footView addSubview:self.footerLabel];
    self.TBSearch.tableFooterView = footView;
    //加占位图
    self.maskImgView = [[UIImageView alloc]initWithFrame:CGRectMake((kDeviceScreenWidth - 88)*0.5, (kDeviceScreenHeight - 103)*0.5, 88, 103)];
    self.maskImgView.image = [UIImage imageNamed:@"icon_searchresult"];
    self.maskImgView.hidden = YES;
    [self.view addSubview:self.maskImgView];
}
#pragma mark - 清除历史记录
- (IBAction)deleteSearchHistorAction:(UIButton *)sender {
    
    [self.historyList removeAllObjects];
    [kUserDefaults removeObjectForKey:@"history"];
    [self.mainTableView reloadData];
}
#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([tableView isEqual:self.mainTableView]) {
        return self.historyList.count;
    }
    return self.searchResultList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView isEqual:self.mainTableView]) {
        WKTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
        cell.textLabel.text = self.historyList[indexPath.row];
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        return cell;

    }
    NSString *cellIdentifier = @"searchCell";
    WKSearchResultCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        [tableView registerNib:[UINib nibWithNibName:@"WKSearchResultCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
    cell.model = self.searchResultList[indexPath.row];
    
    return cell;
    
}
#pragma mark - 代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([tableView isEqual:self.mainTableView]) {
        self.TFsearch.text = self.historyList.mutableCopy[indexPath.row];
        [self.TFsearch resignFirstResponder];
        [self.TFsearch endEditing:YES];
        [self loadSearchData];
        [self searchAction];

    }else if ([tableView isEqual:self.TBSearch]){
        NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
        WKSearchResultCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.model = self.searchResultList[indexPath.row];
        NSString *urlStr = [NSString stringWithFormat:@"%@/andriodwk/course/courseid/%@/userid/%@",kTestMainUrl,cell.model.section_id,userid];
        NSLog(@"单个课程地址：%@",urlStr);
        WKHomeViewController *homeVC = [[WKHomeViewController alloc]init];
        homeVC.isCollection = YES;
        homeVC.urlStr = urlStr;
        homeVC.userId = userid;
        homeVC.collectionBlock = ^{
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        };
        [self.navigationController pushViewController:homeVC animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView isEqual:self.mainTableView]) {
        return 44;
    }
    return 120;
}
#pragma mark - 回收键盘
- (void)hideenKeyboard:(UITapGestureRecognizer*)tap{
    [self.TFsearch resignFirstResponder];
    [self.TFsearch endEditing:YES];
    
}
#pragma mark - 点击删除文字
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    
    self.searchResultList = [NSArray array];
    [self.TBSearch reloadData];
    self.mainTableView.hidden = NO;
    self.headerView.hidden = NO;
    self.searchHistor.hidden = NO;
    self.deleteHistorBtn.hidden = NO;
    self.TBSearch.hidden = YES;
    self.maskImgView.hidden = YES;
    self.titleView.hidden = YES;
    self.lineView.hidden = YES;
    [self.TFsearch resignFirstResponder];
    [self.TFsearch endEditing:YES];
    [self.view endEditing:YES];
    [self.view resignFirstResponder];
    return YES;
}
#pragma mark - 监听搜索框文字
- (void)textfiledChangeAction:(NSNotification*)nofi{
    
    if (self.TFsearch.text.length == 0) {
        self.searchResultList = [NSArray array];
        [self.TBSearch reloadData];
        self.mainTableView.hidden = NO;
        self.headerView.hidden = NO;
        self.searchHistor.hidden = NO;
        self.deleteHistorBtn.hidden = NO;
        self.TBSearch.hidden = YES;
        self.maskImgView.hidden = YES;
        self.titleView.hidden = YES;
        self.lineView.hidden = YES;
        [self.TFsearch resignFirstResponder];
        [self.TFsearch endEditing:YES];
        [self.view endEditing:YES];
        [self.view resignFirstResponder];
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.TFsearch resignFirstResponder];
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
}
#pragma mark - 返回
- (void)backAction:(UIButton*)sender{
    [WKPlayerViewController removeObserverBlocks];
    [self.TFsearch resignFirstResponder];
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    WKHomeViewController *homeVC = [[WKHomeViewController alloc]init];
    homeVC.userId = userid;
    WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:homeVC];
     [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
    
    //[self dismissViewControllerAnimated:NO completion:nil];
}
- (UITextField *)TFsearch{
    
    if (_TFsearch == nil) {
        _TFsearch = [[UITextField alloc]initWithFrame:CGRectMake(50, 7, kDeviceScreenWidth - 50 -35-20, self.navgationBar.height - 10)];
        _TFsearch.clearButtonMode = UITextFieldViewModeWhileEditing;
        _TFsearch.placeholder = @"知识点";
        _TFsearch.borderStyle = UITextBorderStyleNone;
        _TFsearch.returnKeyType = UIReturnKeySearch;
        _TFsearch.delegate = self;
        _TFsearch.backgroundColor = RGBColor(238, 238, 238);
        [_TFsearch setAutocorrectionType:UITextAutocorrectionTypeNo];
        [_TFsearch setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        UIView *leftView = [[UIView alloc] init];
        leftView.frame = CGRectMake(0, 0, 15, 0);
        _TFsearch.leftView = leftView;
        _TFsearch.leftViewMode = UITextFieldViewModeAlways;
        _TFsearch.layer.cornerRadius = 15;
        _TFsearch.layer.masksToBounds = YES;
    }
    return _TFsearch;
}
- (UIButton *)btnBack{
    if (_btnBack == nil) {
        _btnBack = [UIButton  buttonWithType:UIButtonTypeCustom];
        _btnBack.frame = CGRectMake(5, (44-35)*0.5, 35, 35);
        [_btnBack setImage:IMG(@"icon_return") forState:UIControlStateNormal];
        [_btnBack setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _btnBack.titleLabel.font = [UIFont systemFontOfSize:15];
        [_btnBack addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnBack;
}
- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
}
    
@end
